package com.xcw.jac.multithreadeddownloader.core;

import com.xcw.jac.multithreadeddownloader.constant.Constant;
import com.xcw.jac.multithreadeddownloader.utils.HttpUtils;
import com.xcw.jac.multithreadeddownloader.utils.LogUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/**
 * @author xcw
 * @date 2023/8/14 13:20
 * @description 分片下载任务
 */
public class DownloaderTask implements Callable<Boolean> {

    private String url;

    private long startPos;

    private long endPos;

    private long part;

    private CountDownLatch count;

    public DownloaderTask() {
    }

    public DownloaderTask(String url, long startPos, long endPos, long part, CountDownLatch count) {
        this.url = url;
        this.startPos = startPos;
        this.endPos = endPos;
        this.part = part;
        this.count = count;
    }

    @Override
    public Boolean call() throws Exception {
        // 获取文件名称
        String httpFileName = HttpUtils.getHttpFileName(url);
        // 分块的文件名称
        httpFileName = Constant.DEFAULT_PATH + httpFileName + Constant.FILE_SUFFIX + part;

        // 获取分快下载的链接
        HttpURLConnection httpURLConnection = HttpUtils.getHttpURLConnection(this.url, this.startPos, this.endPos);
        try (
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(inputStream);
                RandomAccessFile fos = new RandomAccessFile(httpFileName, "rw");
        ) {
            byte[] buffer = new byte[Constant.BYTE_SIZE];
            int len = -1;
            while ((len = bis.read(buffer)) != -1){
                // 累加 1秒内数据之和
                DownLoadInfoThread.downSize.add(len);
                fos.write(buffer, 0, len);
            }
        } catch (FileNotFoundException e) {
            LogUtils.error("下载的文件不存在 {}", url);
        } catch (Exception e) {
            LogUtils.error("下载时出现异常");
        } finally {
            httpURLConnection.disconnect();
            count.countDown();
        }
        return null;
    }
}
